<?php
/**
 * Created by VS code.
 * User: liuhong
 * Date: 2019-08-29
 * Time: 14:39
 */


namespace app\api\controller;

use app\common\model\Goods as GoodsModel;
use app\service\OrderService;
use app\common\model\Order as OrderModel;
use app\common\model\Comment as CommentModel;


class Comment extends Base
{
    //查询商品评论
    public function index(){
        $comments = CommentModel::index();
        if(empty($comments)){
            $this->ajax(200,'暂无评论', []);
        };
        foreach($comments as $k => $v){
            $comments[$k]['picture_list'] = json_decode($comments[$k]['picture_list'], true);
            $comments[$k]['headimgurl'] = $comments[$k]['user']['headimgurl'];
            $comments[$k]['nickname'] = $comments[$k]['user']['nickname'];
            unset($comments[$k]['user']);
        };
        $this->ajax(200, 'success', $comments);
    }

    /**
     * 添加评论
     * @throws \Exception
     */
    public function add(){
        $input = input();
        if(!isset($input['comments']) || empty($input['comments'])){
            $this->ajax(202,'评价内容不能为空');
        }
        //获取订单id是否存在
        if(!isset($input['order_id']) || empty($input['order_id'])){
            $this->ajax(202,'订单信息不存在');
        }else{
            $order_id = $input['order_id'];
            $order_info=OrderService::S()->findOrder(array('id'=>$order_id));
            if($order_info){
                if($order_info['checked']==7){ //已评价
                    $this->ajax(202,'已评价');
                }else if($order_info['checked']!=2){  //非完成状态
                    $this->ajax(202,'订单不能评价');
                }
            }else{
                $this->ajax(202,'订单信息不存在');
            }
        }

//        $goods_list = array_column(json_decode($order_info['goods_list'],true),'id');
        $comments = [];
        foreach ($input['comments'] as $goods){
            $comment['uid'] = $this->uid;
            $comment['rate'] = (isset($goods['rate']) && $goods['rate'])? $goods['rate']: 5;
            $comment['content'] = $goods['content'];
            $comment['order_id'] = $input['order_id'];
            $picture_list = $goods['picture_list'];
            $comment['picture_list'] = json_encode($picture_list);
            $comment['goods_id'] = $goods['goods_id'];
            $comment['guige'] = $goods['guige'];
            $comments[] = $comment;
        }

        //创建新评论
        $commentModel = new CommentModel();
        $ret = $commentModel->saveAll($comments);
        if(empty($ret)){
            $this->ajax(202,'评价失败，请重试');
        }
        //更新订单的状态
        $save=['checked' => 7]; //已评价
        $re=OrderService::S()->saveOrder($save,array('id'=>$order_id));
        if($re){
            $this->ajax(200,'评价成功');
        }
        $this->ajax(202,'评价败，请重试');
    }
}

?>